//
//  mainViewController.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/8.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit

class mainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
       addChildViewControllers()
    
    }
//    5 子图层布置完毕后调用，添加到父控件上
   override func viewDidLayoutSubviews() {
        
        setUpCompoButton()
    }
    
    //4 监听按钮点击
     func clickComeposedButton()
    {
        let vc = UserAccount.userLogon ? ComPoseViewController() : OAuthViewController()
       let nav = UINavigationController(rootViewController: vc)
        
        
        presentViewController(nav, animated: true, completion: nil)
        
    }
    
    //3 设置按钮位置，
   private func setUpCompoButton()
    {
       let w = tabBar.bounds.width / CGFloat (viewControllers!.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        componButton.frame = CGRectOffset(rect, w * 2, 0)
        
    }

    private func addChildViewControllers() {
        
        addChildViewController(homeTableViewController(), title: "首页", imageName: "tabbar_home")
        
        addChildViewController(discoverTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        // 1 添加到tabar上uiview，进行占位
        addChildViewController(UIViewController())
        
        addChildViewController(messageTableViewController(), title: "发现", imageName: "tabbar_discover")
        
        addChildViewController(profileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    
    //封装好的接口,供外部直接调动
    private func addChildViewController(vc: UIViewController,title:String,imageName:String) {
        
//  let vc = homeTableViewController()
    tabBar.tintColor = UIColor.orangeColor()
    
    vc.title = title
    vc.tabBarItem.image = UIImage(named: imageName)
    let nav = UINavigationController(rootViewController: vc)

        self.tabBar.subviews
    addChildViewController(nav)
   
    }
    
    //2 懒加载控件
    lazy private var componButton: UIButton = {
        
       let button = UIButton()
        
        //设置按钮背景图片和按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
         button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        
         self.tabBar.addSubview(button)
//        监听按钮点击
        button.addTarget(self, action: "clickComeposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}
